package com.ybxx.core.web.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ImageValidatorServlet extends HttpServlet {

	 	 ImageGenerator imageGenerator = new ImageGenerator();   
	     @Override  
	     protected void doPost(HttpServletRequest request,   
	             HttpServletResponse response) throws ServletException, IOException {   
	         doGet(request, response);   
	     }   
	     @Override  
	     protected void doGet(HttpServletRequest request,   
	             HttpServletResponse response) throws ServletException, IOException {   
	         response.reset();   
	         // 设置页面不缓存   
	         response.setHeader("Pragma", "No-cache");   
	         response.setHeader("Cache-Control", "no-cache");   
	         response.setDateHeader("Expires", 0);   
	         response.setContentType("image/gif");   
	            
	         // 生成的图片   
	         BufferedImage image = imageGenerator.createImage();   
	         // 随机字符串   
	         String randString = imageGenerator.getRandString();   
	         HttpSession session = request.getSession(true);   
	                    
	         session.setAttribute("randString", randString);   
	         // Servlet输出流   
	         OutputStream out = response.getOutputStream();   
	         // 将图片写入到输出流中去   
	         ImageIO.write(image, "JPG", out);   
	         // 制刷新   
	         out.flush();   
	         // 关闭输出流   
	         out.close();   
	     }   
	 }  
